function interceptor(result) {
  if (result.code == 401) {
    location.replace('/login.html')
  } else {
    return result;
  }
}

function query1() {
  fetch('/api/users/info', {
    headers: { 'Content-Type': 'application/json' },
    method: 'post',
    body: JSON.stringify({ abc: 123 })
  })
    .then(response => response.json())
    .then(result => {
      console.log(interceptor(result))
    })
}

function query2() {
  fetch('/api/users/rows', {
    headers: { 'Content-Type': 'application/json' },
    method: 'post',
    body: JSON.stringify({ abc: 123 })
  })
    .then(response => response.json())
    .then(result => {
      console.log(interceptor(result))
    })
}

function upload() {
  let formData = new FormData()
  let fileField = document.querySelector('#metadata')
  console.log(fileField)

  formData.append('metadata', fileField.files[0])
  formData.append('appName', 'SMS')

  fetch('/api/metas/import', {
    method: 'post',
    body: formData
  })
    .then(response => response.json())
    .then(result => {
      document.querySelector('#result').innerHTML = JSON.stringify(result)
    })
}

function download(type) {
  if (type == 'open') {
    window.open('/api/metas/file/app/app-metadata.json');
  } else {
    fetch('/api/metas/file/app/app-metadata.json')
      .then(response => response.blob())
      .then(result => {
        console.log(result)
      })
  }

}

function login() {
  let name = document.querySelector('#username').value;
  let password = document.querySelector('#password').value;
  fetch('/login', {
    method: 'post',
    body: JSON.stringify({ name, password })
  })
    .then(response => response.json())
    .then(result => {
      if (result.code == 200) {
        location.replace('/index.html')
      }
    })
}

function logout() {
  fetch('/logout')
    .then(response => response.json())
    .then(result => {
      console.log(interceptor(result))
    })
    .catch(function (err) {
      console.log(err)
    })
}

function addUser() {
  let name = document.querySelector('#username').value;
  let password = document.querySelector('#password').value;
  fetch('/api/addUser', {
    method: 'post',
    body: JSON.stringify({ name, password })
  })
    .then(response => response.json())
    .then(result => {
      console.log(interceptor(result))
    })
}

function updateUser() {
  let name = document.querySelector('#username').value;
  let password = document.querySelector('#password').value;
  fetch('/api/updateUser', {
    method: 'post',
    body: JSON.stringify({ name, password })
  })
    .then(response => response.json())
    .then(result => {
      console.log(interceptor(result))
    })
}

function getUser() {
  fetch('/api/users/rows', {
    method: 'get',
  })
    .then(response => response.json())
    .then(result => {
      console.log(interceptor(result))
    })
}

